package com.ruoyi.web.controller.api;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.AdminPrizeConfig;
import com.ruoyi.system.domain.AdminPrizeRecord;
import com.ruoyi.system.service.IAdminPrizeConfigService;
import com.ruoyi.system.service.IAdminPrizeRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @program: ruoyi
 * @description: 开奖接口
 * @author: Mr.sun
 * @create: 2020-09-23 09:17
 **/
@Api("彩球H5接口")
@RestController
@RequestMapping("/api/prize")
public class AdminApiController extends BaseController {

    @Autowired
    private IAdminPrizeRecordService iAdminPrizeRecordService;

    @Autowired
    private IAdminPrizeConfigService iAdminPrizeConfigService;


    @ApiOperation("测试方法")
    @GetMapping("/test")
    public void test(){
        System.out.println("测试接口");
    }

    @ApiOperation("获取已开奖号码的列表")
    @GetMapping("/getPrizeList")
    public Map<String, Object> getPrizeList(String searchTime){
        logger.info("===========getPrizeList==========","获取已开奖号码的列表");
        startPage();
        if (searchTime==null || searchTime.equals("")) {
            searchTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getNowDate());
        }
        List<AdminPrizeRecord> prizeList = iAdminPrizeRecordService.getPrizeList(searchTime);
        List<String[]> totalList = new ArrayList<>();
        for (AdminPrizeRecord prizeRecord: prizeList) {
            String[] ss = new String[8];
            prizeRecord.setStrPrizeTime(DateUtils.parseDateToStr("HH:mm",prizeRecord.getPrizeTime()));
            prizeRecord.setStrLotteryNumber(prizeRecord.getLotteryNumber().split(","));

            String[] strs = prizeRecord.getLotteryNumber().split(",");
            int sum = 0;
            for(String s : strs){
                sum += Integer.parseInt(s);
            }
            ss[0]=sum+"";
            if (sum >= 85) { ss[1]= "大"; } else { ss[1]= "小";}
            if (sum % 2 == 0) { ss[2]= "双"; } else { ss[2]= "单";}
            if (sum%10 >=5) { ss[3]= "尾大"; } else { ss[3]= "尾小";}
            if (Integer.parseInt(strs[4]) % 2 == 0) { ss[4]= "龙"; } else { ss[4]= "虎";}
            if (Integer.parseInt(strs[5]) % 2 == 0) { ss[5]= "龙"; } else { ss[5]= "虎";}
            if (Integer.parseInt(strs[6]) % 2 == 0) { ss[6]= "龙"; } else { ss[6]= "虎";}
            if (Integer.parseInt(strs[7]) % 2 == 0) { ss[7]= "龙"; } else { ss[7]= "虎";}
            totalList.add(ss);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.SUCCESS);
        map.put("msg", "查询成功");
        map.put("rows", prizeList);
        map.put("rows2", totalList);
        map.put("total", new PageInfo(prizeList).getTotal());
        return map;
    }

    @ApiOperation("获取即将要开奖号码和下期开奖的时间")
    @GetMapping("/getCurrentPrizeInfo")
    public AjaxResult getCurrentPrizeInfo(){
        logger.info("===========getCurrentPrizeInfo==========","获取即将要开奖号码和下期开奖的时间");
        HashMap<String, Object> hashMap = new HashMap<>();
        Long nextTime;
        AdminPrizeConfig stateInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("state");
        AdminPrizeRecord currentPrizeInfo = iAdminPrizeRecordService.getCurrentPrizeInfo();
        AdminPrizeConfig intervalInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("interval");
        String searchTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", DateUtils.getNowDate());
        int interval = Integer.valueOf(intervalInfo.getConfigValue()).intValue();
        List<AdminPrizeRecord> prizeList = iAdminPrizeRecordService.getPrizeList(searchTime);
        String[] strings = currentPrizeInfo.getLotteryNumber().split(",");
        currentPrizeInfo.setStrLotteryNumber(strings);


        if(strings != null && strings.length>0){

            String[] ss = new String[8];
            int sum = 0;
            for(String s : strings){
                sum += Integer.parseInt(s);
            }
            ss[0]=sum+"";
            if (sum >= 85) { ss[1]= "大"; } else { ss[1]= "小";}
            if (sum % 2 == 0) { ss[2]= "双"; } else { ss[2]= "单";}
            if (sum%10 >=5) { ss[3]= "尾大"; } else { ss[3]= "尾小";}
            if (Integer.parseInt(strings[4]) % 2 == 0) { ss[4]= "龙"; } else { ss[4]= "虎";}
            if (Integer.parseInt(strings[5]) % 2 == 0) { ss[5]= "龙"; } else { ss[5]= "虎";}
            if (Integer.parseInt(strings[6]) % 2 == 0) { ss[6]= "龙"; } else { ss[6]= "虎";}
            if (Integer.parseInt(strings[7]) % 2 == 0) { ss[7]= "龙"; } else { ss[7]= "虎";}
            currentPrizeInfo.setTotalString(ss);
        }

//        currentPrizeInfo.setSurplusPrizePeriod(getDatePoor(currentPrizeInfo.getPrizeTime(),interval));
        currentPrizeInfo.setSurplusPrizePeriod(getSurplusNumber(currentPrizeInfo.getPrizeTime(),interval));
        currentPrizeInfo.setTodayPrizePeriod(prizeList.size());
        currentPrizeInfo.setStrPrizeTime(DateUtils.parseDateToStr("HH:mm",currentPrizeInfo.getPrizeTime()));
        if (stateInfo.getConfigValue().equals("2")) {
            return AjaxResult.success(currentPrizeInfo);
        }
        AdminPrizeRecord nextPrizeInfo = iAdminPrizeRecordService.selectAdminPrizeRecordByPrizeTime();
        nextTime=getTimeStamp(nextPrizeInfo.getPrizeTime(),DateUtils.getNowDate());
        currentPrizeInfo.setNextTime(nextTime);
        return AjaxResult.success(currentPrizeInfo);
    }

    public static Integer getSurplusNumber(Date time,Integer interval) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = null;
//        try {
//            // 注意格式需要与上面一致，不然会出现异常
//            date = sdf.parse("2020-09-29 00:10:00");
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        System.out.println("字符串转换成时间:" + date);
//
//        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
//        sdf1.format(date);
//
//        System.out.println(getDatePoor(date,interval));


        String ymd = DateUtils.parseDateToStr("yyyy-MM-dd", time);

        LocalDate localDate=LocalDate.now();
        //指定时间，注意，如果使用下面的这种获取方式，一定要注意必须为严格的yy-mm-dd,9月必须为09,1号必须为01，否则会报错
        LocalDate localDate1=LocalDate.parse(ymd);
        //获取两个日期的天数差，为前一个减去后一个，正数则为前面的日期较晚
        int i=localDate.compareTo(localDate1);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(time.toInstant(), ZoneId.systemDefault());


        if(i>0 || //如果超过一天，直接根据一天时间除以开奖时间间隔再加1得出剩余期数
                LocalDateTime.now().compareTo(localDateTime.plusMinutes(interval))==1//如果暂停过，当前时间会大于上次开奖时间加开奖时间间隔，还是用当前时间去计算
            ){
            LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
            Long minutes = ChronoUnit.MINUTES.between(LocalDateTime.now(), midnight);
            Long number = (minutes/interval)+1;
            return number.intValue();
        }
        LocalDateTime localDateTime1 = localDateTime ;
        if(LocalDateTime.now().compareTo(localDateTime1.plusMinutes(interval))==1){
            //大于
            LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
            Long minutes = ChronoUnit.MINUTES.between(LocalDateTime.now(), midnight);
            Long number = (minutes/interval)+1;
            return number.intValue();
        }

        //不超过一天就拿上次开奖时间计算剩余开奖期数
        String maxTime = ymd + " 23:59:59";

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime.parse(maxTime, df);

        Long minutes = ChronoUnit.MINUTES.between(localDateTime, LocalDateTime.parse(maxTime, df));
        Long number = minutes/interval;
        return number.intValue();
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            // 注意格式需要与上面一致，不然会出现异常
            date = sdf.parse("2020-09-28 03:59:00");
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("字符串转换成时间:" + date);
        System.out.println(getSurplusNumber(date,5));
    }


    public static Integer getDatePoor(Date time,Integer interval) {
        long current = System.currentTimeMillis();
        long zero = current/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset()+24*60*60*1000-1;
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long longTime = time.getTime();
        long diff = zero-longTime;
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        Long resultMin=day*24*60+hour*60+min;
        Long result=resultMin/interval;
        return result.intValue();

    }


    public static long getTimeStamp(Date endDate, Date nowDate) {
        long diff = endDate.getTime() - nowDate.getTime();
        return diff;
    }
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
         long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
         long sec = diff % nd % nh % nm / ns;
         Long resultMin=day*24*60+hour*60+min;
        String strMin;
        if (resultMin>=10) {
            strMin=resultMin.toString();
        }else {
            strMin="0"+resultMin.toString();
        }
        String result=strMin+":"+sec;
        return result;
    }

}
